<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <script>



        ajax({
            url : '../php/1.php' ,
            type : 'get' ,
        }).then(data => {
            console.log(data);
        })











        function ajax(options) {
            const {
                url ,
                type ,
                data = {} ,
                async = true,
                dataType = 'json'
            } = options ;

            let params = '';
            // 遍历data
            for (let key in data) {
                params += `${key}=${data[key]}&`;
            }
            params = params.substring(0, params.length - 1);


            const p = new Promise((resolve, reject) => {
                // 异步的程序
                const xhr = new XMLHttpRequest();

                // 判断请求的方式
                if (type.toLowerCase() === 'get') {
                    xhr.open(type, url + '?' + params, true);
                    xhr.send();
                }
                else if (type.toLowerCase() === 'post') {
                    xhr.open(type, url, true);
                    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
                    xhr.send(params);
                }


                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        // resolve('成功啦') ;
                        let data = xhr.responseText;
                        if(dataType === 'json') {
                            data = JSON.parse(data) ;
                        }
                        resolve(data);
                    }
                }
            });

            return p
        }



    </script>

</body>

</html>